const http = require("http");
const fs = require("fs");
const path = require("path");
/**
 * 搭建静态资源服务器
 */

const mimes = {
  html: "text/html",
  css: "text/css",
  js: "application/javascript",
  gif: "image/gif",
  jpeg: "image/jpeg",
  png: "image/png",
};

// 创建一个服务
const server = http.createServer((request, response) => {
  //   console.log("request", request);
  // 解析请求类型
  if (request.method !== "GET") {
    response.statusCode = 405;
    response.end("405 request methods is not allowed");
  }
  // 解析文件路径
  const url = new URL(request.url, "http://127.0.0.1:9000");
  const filePath = __dirname + "/static" + url.pathname; // 文件路径     /static 为静态文件根目录
  console.log("filePath", filePath);

  fs.readFile(filePath, (err, data) => {
    if (err) {
      //   console.log("err", err);
      response.setHeader("content-type", "text/html;charset=utf-8");
      // 处理不同类型的错误
      switch (err.code) {
        case "ENOENT":
          response.statusCode = 404;
          response.end("文件未找到");
          break;

        default:
          response.statusCode = 500;
          response.end("服务端错误");
          break;
      }
      return;
    }

    // 根据不同的文件类型 设置不同的响应头
    console.log(request.url);
    // application/octet-stream（任意的二进制数据）
    const extname = path.extname(request.url).slice(1);
    const extType = mimes[extname];
    console.log("extType", extType);

    response.end(data);
  });
});

// 监听接口
server.listen(9000, () => {
  console.log("服务启动了");
});
